package com.banshuibao.bsb_android.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.banshuibao.bsb_android.BuildConfig;
import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.MainActivity;
import com.banshuibao.bsb_android.MyApplication;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.RegisterModel;
import com.banshuibao.bsb_android.model.SendSmsModel;
import com.banshuibao.bsb_android.uploadhead.ClipImageActivity;
import com.banshuibao.bsb_android.uploadhead.view.CircleImageView;
import com.banshuibao.bsb_android.util.Base64ForImg;
import com.banshuibao.bsb_android.util.ImageUtil;
import com.banshuibao.bsb_android.util.MD5;
import com.banshuibao.bsb_android.util.PictureUtil;
import com.banshuibao.bsb_android.util.XToast;

import java.io.File;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegisterActivity extends PermissionBaseActivity implements View.OnClickListener {

    private ImageView headImage;
    private TextView headImage_tv;
    private EditText phoneNumber;
    private EditText register_number;
    private EditText register_yanzhengma;
    private EditText register_password;
    private EditText mName;
    private ImageView image_number;
    private Button getNumber;
    private CheckBox checkBox;
    private TextView user_tv;
    private Button register_btn;

    public int isSelected = 1;

    //请求相机
    private static final int REQUEST_CAPTURE = 100;
    //请求相册
    private static final int REQUEST_PICK = 101;
    //请求截图
    private static final int REQUEST_CROP_PHOTO = 102;
    //请求访问外部存储
    private static final int READ_EXTERNAL_STORAGE_REQUEST_CODE = 103;
    //请求写入外部存储
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 104;
    //头像1
    private CircleImageView headImage1;
    //头像2
    private ImageView headImage2;
    //调用照相机返回图片文件
    private File tempFile;
    //请求验证码的唯一标识
    private String string;
    //获取的短信唯一标识
    private String smsMessageSid;
    private RegisterModel.body body = new RegisterModel.body();;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    //获取验证码倒计时
    CountDownTimer timer = new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            getNumber.setText(millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {
            getNumber.setEnabled(true);
            getNumber.setText("重新获取");
            getNumber.setTextSize(14);
        }
    };

    private void initView() {
        setTitleText("注册");
        headImage = (ImageView) findViewById(R.id.login_iv);
        headImage_tv = (TextView) findViewById(R.id.login_tv);
        phoneNumber = (EditText) findViewById(R.id.register_phoneNumber);
        mName = (EditText) findViewById(R.id.register_name);
        register_number = (EditText) findViewById(R.id.register_number);
        register_yanzhengma = (EditText) findViewById(R.id.register_yanzhengma);
        register_password = (EditText) findViewById(R.id.register_password);
        image_number = (ImageView) findViewById(R.id.imageView);
        getNumber = (Button) findViewById(R.id.register_huoqu_btn);
        checkBox = (CheckBox) findViewById(R.id.checkbox);
        user_tv = (TextView) findViewById(R.id.user_http);
        register_btn = (Button) findViewById(R.id.register_btn);
        headImage.setOnClickListener(this);
        headImage_tv.setOnClickListener(this);
        getNumber.setOnClickListener(this);
        user_tv.setOnClickListener(this);
        register_btn.setOnClickListener(this);
        image_number.setOnClickListener(this);
        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    register_btn.setClickable(true);
                } else {
                    register_btn.setClickable(false);
                    XToast.showToast(RegisterActivity.this, "请同意用户协议");
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getDataPost();
    }

    private String getTime() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        Random random = new Random();
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand += rand;
        }
        return "code_" + sRand + String.valueOf(time);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //点击头像
            case R.id.login_iv:
                GetHead(view);
                break;
            //点击上传
            case R.id.login_tv:
                GetHead(view);
                break;
            //点击获取
            case R.id.register_huoqu_btn:
                isSelected = 2;
                String phoneNumber1 = phoneNumber.getText().toString().trim();
                String s = register_number.getText().toString().trim();
                String name = mName.getText().toString().trim();
                if (!TextUtils.isEmpty(name)) {
                    if (isMatchMobilLength(phoneNumber1, 11) && isMobilNo(phoneNumber1)) {
                        if (!TextUtils.isEmpty(s) && s.length() == 4) {
                            setpost(phoneNumber1, s);
                        } else {
                            XToast.showToast(this, "请正确输入右侧数字");
                        }
                    } else {
                        XToast.showToast(this, "输入电话号码有误");
                    }
                }else {
                    XToast.showToast(this, "请先输入您的昵称");
                }
                break;
            //点击用户协议
            case R.id.user_http:
                startActivity(new Intent(this,UserAgreementActivity.class));
                break;
            //点击注册
            case R.id.register_btn:
                String name1 = mName.getText().toString().trim();
                String phone = phoneNumber.getText().toString().trim();
                String number = register_number.getText().toString().trim();
                String yan = register_yanzhengma.getText().toString().trim();
                String password = register_password.getText().toString().trim();
                if (body.getHeadImg() != null) {
                    if (!TextUtils.isEmpty(name1)) {
                        if (!TextUtils.isEmpty(phone) && isMobilNo(phone) && isMatchMobilLength(phone, 11)) {
                            if (!TextUtils.isEmpty(number) && number.length() == 4) {
                                if (isSelected == 2) {
                                    if (!TextUtils.isEmpty(yan)) {
                                        if (!TextUtils.isEmpty(password) && isPassword(password)) {
                                            try {
                                                showProgressDialog();
                                                RegisterPost(name1,phone, number, yan, password);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        } else {
                                            XToast.showToast(this, "请输入正确密码格式");
                                        }
                                    } else {
                                        XToast.showToast(this, "请输入验证码");
                                    }
                                } else {
                                    XToast.showToast(this, "请获取验证码");
                                }
                            } else {
                                XToast.showToast(this, "请正确输入右侧数字");
                            }
                        } else {
                            XToast.showToast(this, "请输入正确手机号");
                        }
                    }else {
                        XToast.showToast(this, "请输入您的昵称");
                    }
                }else {
                    XToast.showToast(this, "请先上传头像");
                }
                break;
            case R.id.imageView:
                getDataPost();
                break;
        }
    }

    private void getDataPost() {
        string = getTime();
        ImageUtil.loadNumberImage(this, Constants.Url.GET_CODE + string, image_number);
//        LogUtil.e(Constants.Url.GET_CODE + string);
    }

    //注册的接口
    private void RegisterPost(String name,String phone, String number, String yan, String password) throws Exception {
        body.setPhone(phone);
        body.setSmsCode(yan);
        body.setPwd(MD5.encryptMD5ToString(password.getBytes()));
        body.setDeviceType(1);
        body.setSmsMessageSid(smsMessageSid);
        body.setName(name);
        HttpUtil.doPost(Constants.Url.REGISTER, body, new HttpResponse(this,RegisterModel.class) {
            @Override
            public void onResult(Object obj) {
                RegisterModel s = (RegisterModel) obj;
//                LogUtil.e(s);
                RegisterModel.DataBean data = s.getData();
                MyApplication.applicationInstance.setAlias(data.getUuid());
                String role = data.getRole();
                String type = "";
                if(role.equals("2") || role.equals("3")||role.equals("4")){
                    type = "tax";
                }else{
                    type = "user";
                }
                MyApplication.applicationInstance.addTag("1",type);
                saveRegisterInFo(data);
                XToast.showToast(RegisterActivity.this,"注册成功");
                cancelProgressDialog();
                startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                finish();
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                cancelProgressDialog();
            }
        });
    }

    private void saveRegisterInFo(RegisterModel.DataBean data) {
        SharedPreferences.Editor editor = getSharedPreferences("registerInFo", MODE_PRIVATE).edit();
        editor.putString("cookieId",data.getCookieId());
        editor.putString("headImg",data.getHeadImg());
        editor.putString("firmId",data.getFirmId());
        editor.putString("name",data.getName());
        editor.putString("phoneNumber",data.getPhone());
        editor.putString("role",data.getRole());
        editor.putString("vip",data.getVip());
        editor.putFloat("balance", (float) data.getBalance());
//        editor.putString("",data.getBirthday());
        editor.putLong("vipTime",data.getVipTime());
        editor.putString("userId",data.getUuid());
        editor.commit();
    }

    //获取验证码接口
    private void setpost(String phoneNumber, String s) {
        SendSmsModel.body body = new SendSmsModel.body();
        body.setPhone(phoneNumber);
        body.setImgCode(s);
        body.setSendtype("UR");
        body.setCodeMessage(string);
        HttpUtil.doPost(Constants.Url.SEND_SMS, body, new HttpResponse(this,SendSmsModel.class) {
            @Override
            public void onResult(Object obj) {
                timer.start();
                SendSmsModel sendSmsModel = (SendSmsModel) obj;
                smsMessageSid = sendSmsModel.getSmsMessageSid();
            }
        });
    }

    public boolean isMatchMobilLength(String phone, int length) {
        if (!TextUtils.isEmpty(phone)) {
            return phone.length() == length;
        }
        return false;
    }

    public boolean isPassword(String phone) {
        Pattern pattern = Pattern.compile("[0-9a-zA-Z\\d]{6,15}");
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    public boolean isMobilNo(String phone) {
        String repexp = "^[1][345789]\\d{9}";
        Pattern pattern = Pattern.compile(repexp);
        Matcher matcher = pattern.matcher(phone);
        return matcher.matches();
    }

    //取消
    @Override
    protected void onDestroy() {
        timer.cancel();
        super.onDestroy();
    }

    //点击隐藏输入框之外 隐藏输入框
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    public void GetHead(View v) {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_popupwindow, null);
        TextView btnCarema = (TextView) view.findViewById(R.id.btn_camera);
        TextView btnPhoto = (TextView) view.findViewById(R.id.btn_photo);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });

        btnCarema.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限判断
                requestUserPermission(v, Manifest.permission.CAMERA, REQUEST_CAPTURE);
                popupWindow.dismiss();
            }
        });
        btnPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //权限判断
                requestUserPermission(v, Manifest.permission.WRITE_EXTERNAL_STORAGE, REQUEST_PICK);
                popupWindow.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    @Override
    public void successGrantPermission(int requestCode) {
        switch (requestCode) {
            case REQUEST_CAPTURE:
                gotoCamera();
                break;
            case REQUEST_PICK:
                gotoPhoto();
                break;

        }
    }


    /**
     * 跳转到相册
     */
    private void gotoPhoto() {
        //     Log.d("evan", "*****************打开图库********************");
        //跳转到调用系统图库
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), REQUEST_PICK);
    }


    /**
     * 跳转到照相机
     */
    private void gotoCamera() {
        //    Log.d("evan", "*****************打开相机********************");
        //创建拍照存储的图片文件
        tempFile = new File(checkDirPath(Environment.getExternalStorageDirectory().getPath() + "/image/"), System.currentTimeMillis() + ".jpg");
        String authority = "com.banshuibao.bsb_android.fileprovider";
        //跳转到调用系统相机
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //设置7.0中共享文件
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(RegisterActivity.this, BuildConfig.APPLICATION_ID + ".fileprovider", tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        startActivityForResult(intent, REQUEST_CAPTURE);
    }


    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case REQUEST_CAPTURE: //调用系统相机返回
                if (resultCode == RESULT_OK) {
                    //      Log.e("TAG", "**********camera uri*******" + Uri.fromFile(tempFile).toString());
                    //       Log.e("TAG", "**********camera path*******" + getRealFilePathFromUri(RegisterActivity.this, Uri.fromFile(tempFile)));
                    gotoClipActivity(Uri.fromFile(tempFile));
                }
                break;
            case REQUEST_PICK:  //调用系统相册返回
                if (resultCode == RESULT_OK) {
                    Uri uri = intent.getData();
                    //    Log.e("TAG", "**********pick path*******" + getRealFilePathFromUri(RegisterActivity.this, uri));
                    gotoClipActivity(uri);
                }
                break;
            case REQUEST_CROP_PHOTO:  //剪切图片返回
                if (resultCode == RESULT_OK) {
                    final Uri uri = intent.getData();
                    if (uri == null) {
                        return;
                    }
                    String cropImagePath = getRealFilePathFromUri(getApplicationContext(), uri);
                    Bitmap bitmap = BitmapFactory.decodeFile(cropImagePath);
                    //  writeSD(bitmap);
                    headImage.setImageBitmap(PictureUtil.makeRoundCorner(bitmap));
                    //此处后面可以将bitMap转为二进制上传后台网络
                    //......
                    String head = Base64ForImg.imgToBase64(cropImagePath);
                    // eum.setHeadImage(head);//修改头像
                    body.setHeadImg(head);
                }
                break;
        }
    }


    /**
     * 打开截图界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        // Log.e("TAG", "**********clip path*******" + getRealFilePathFromUri(RegisterActivity.this, uri));
        Intent intent = new Intent();
        intent.setClass(this, ClipImageActivity.class);
        intent.putExtra("type", 1);
        intent.setData(uri);
        startActivityForResult(intent, REQUEST_CROP_PHOTO);
    }


    /**
     * 根据Uri返回文件绝对路径
     * 兼容了file:///开头的 和 content://开头的情况
     */
    public static String getRealFilePathFromUri(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

}
